package com.baymax.study.tuLing.nio;

import lombok.SneakyThrows;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

/**
 * @author baymax
 * @since 2025-06-27
 */
public class NioNonBlockDemo {
    public static final int PORT = 60001;

    static class Server {
        public static void main(String[] args) throws Exception {
            // 单线程服务器，nio的非阻塞模式
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false); // 设置ServerSocketChannel非阻塞
            ssc.bind(new InetSocketAddress(PORT));
            System.out.println("服务器启动成功");

            ByteBuffer byteBuffer = ByteBuffer.allocate(16);
            List<SocketChannel> socketChannels = new ArrayList<>();
            while (true) {
                SocketChannel sc = ssc.accept(); // 非阻塞
                if (sc != null) {
                    System.out.println("连接成功");
                    sc.configureBlocking(false); // 设置SocketChannel非阻塞
                    socketChannels.add(sc);
                }
                for (SocketChannel channel : socketChannels) {
                    int length = channel.read(byteBuffer);// 非阻塞
                    if (length > 0) {
                        byteBuffer.flip();
                        System.out.println(StandardCharsets.UTF_8.decode(byteBuffer));
                        byteBuffer.clear();
                    }
                }
            }
        }
    }

    static class Client {
        public static void main(String[] args) throws Exception {
            SocketChannel sc = SocketChannel.open();
            sc.connect(new InetSocketAddress("127.0.0.1", PORT));
            System.out.println("连接成功");

            TimeUnit.SECONDS.sleep(2);
            sc.write(ByteBuffer.wrap("hello client".getBytes()));
            System.out.println("数据发送完毕");
            sc.close();
        }
    }
}
